<?php
/**
 * Created by PhpStorm.
 * User: caviar
 * Date: 2019/10/31
 * Time: 16:25
 */

namespace app\http\middleware;


use app\lib\exception\ParameterException;
use think\cache\driver\Redis;

class ImposeRequest
{
    /**
     * 限制请求 同一Ip 同一接口 多少秒内请求多少次
     * @param $request
     * @param \Closure $next
     * @return mixed
     * @throws ParameterException
     */
    public function handle($request, \Closure $next)
    {
        $k = [
            'ip'    =>  $request->ip(),
            'url'   =>  $request->url(),
        ];
        $redis = new Redis();

        $rTime = $redis->get($k['ip'].$k['url']);


        if ((time() - $rTime) < 3) {
            throw new ParameterException('三秒内相同的接口只能访问一次');
        }

        $redis->set($k['ip'].$k['url'],time());
        return $next($request);
    }








}